package com.ada.trie;

import java.util.HashMap;
import java.util.Map;


public class SensitiveWordFilter {
    private TrieNode root = new TrieNode();
    private char replacementChar = '*'; // 替换字符，默认为 '*'

    public void setReplacementChar(char replacementChar) {
        this.replacementChar = replacementChar;
    }

    // 添加敏感词到Trie树
    public void addSensitiveWord(String word) {
        TrieNode node = root;
        for (char c : word.toCharArray()) {
            if (!node.containsKey(c)) {
                node.put(c, new TrieNode());
            }
            node = node.get(c);
        }
        node.setEnd(true);
    }

    // 检测文本中是否包含敏感词并替换
    public String filterText(String text) {
        char[] textChars = text.toCharArray();
        for (int i = 0; i < textChars.length; i++) {
            TrieNode node = root;
            int j = i;
            while (j < textChars.length && node.containsKey(textChars[j])) {
                node = node.get(textChars[j]);
                if (node.isEnd()) {
                    // 替换敏感词
                    for (int k = i; k <= j; k++) {
                        textChars[k] = replacementChar;
                    }
                }
                j++;
            }
            i = j - 1;
        }
        return new String(textChars);
    }

    public static void main(String[] args) {
        SensitiveWordFilter filter = new SensitiveWordFilter();
        filter.addSensitiveWord("敏感词1");
        filter.addSensitiveWord("敏感词2");

        String text1 = "这是一个包含敏感词1的文本。";
        String text2 = "这是一个正常的文本。";

        String filteredText1 = filter.filterText(text1);
        String filteredText2 = filter.filterText(text2);

        System.out.println("文本1： " + filteredText1);
        System.out.println("文本2： " + filteredText2);
    }
}
